<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { useCodeStore } from "@/stores/code.js";
import {
  appCategory,
  supplierSelector,
  productCreate,
  appProductDetail,
  appProductDisable,
  appProductEnable,
  productUpdate,
  appProductCode,
  appUnit,
} from "@/services/goods";
import { base_URL } from "@/utils/http";
import homeStart from "@/pages/goods/static/sacd.png";

// import tabbarView from "../components/tabbar.vue";
const codeStore = useCodeStore();

console.log("codeStore", codeStore.code);

const formMode = ref(null);
const form = ref({
  barCode: "",
  name: "",
  categoryId: "",
  image: "",
  stock: "",
  salePrice: "",
  purchasePrice: "",

  wholePrice: "",

  skuCode: "",
  unit: "",
  supplierId: "",
  memberPrice: "",
  supplierName: "",
  valuationType: 0,
  barCodeList: [],
  remark: "",

  //、
  username: "",
  password: "",
  categoryName: "",
  price: "",
  ol_price: "",
});
const checked = ref(false);
const showBarCode = ref(false);
//类型
const type = ref("");
// id
const id = ref("");

onLoad((options) => {
  console.log(options);
  type.value = options.type ? options.type : "add";
  id.value = options.id ? options.id : "";
  if (id.value) {
    getProduceDet();
  }
  codeStore.setcode("");
  getAppUnit();
});

onShow(() => {
  form.value.barCode = codeStore.code;
  console.log(codeStore.code);

  // showToast("扫码结果" + codeStore.code);
});
//商品单位
const unitList = ref([]);
const getAppUnit = () => {
  appUnit({}).then((res) => {
    console.log(res);
    unitList.value = res.data;
  });
};

//单选
const onRadioChangeFun = (e) => {
  console.log(e);
  if (e == 1) {
    checked.value = true;
  } else {
    checked.value = false;
  }
};

//商品详情
const getProduceDet = async () => {
  console.log(id.value);
  try {
    let res = await appProductDetail({ id: id.value });
    if (res.code == 200) {
      form.value = res.data;
      fileList.value = [{ url: res.data.image }];
      form.value.checked = res.data.memberPrice > 0 ? true : false;
      purchasePricevalue.value = res.data.purchasePrice;
      form.value.barCodeList = form.value.barCodeList
        ? form.value.barCodeList
        : [];
    } else {
      showToast(res.msg);
    }
  } catch (e) {
    showToast(e.msg);
  }
};

const pageslenght = ref(0);
onMounted(() => {
  getAppCategory();
  getSupplierSelector();
});
const fileList = ref([]);

const columns = ref([]);
const showPicker = ref(false);
const showUnitPicker = ref(false);
const pickerValue = ref([]);
const purchasePricevalue = ref(0);

const onCareConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.categoryName = selectedOptions[selectedOptions.length - 1]?.name;
  form.value.categoryId = selectedValues[selectedValues.length - 1];

  pickerValue.value = selectedValues;
  showPicker.value = false;
};
const scanCode = async () => {
  try {
    let res = await appProductCode();
    console.log(res);
    if (res.code == 200) {
      form.value.barCode = res.data.code;
    } else {
      showToast(res.msg);
    }
  } catch (error) {}
};
const shaScanCode = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index" });
  // #endif
};

const saveFun = () => {
  console.log("保存");
  console.log(form.value);
  // console.log(fileList.value[0].content);
  formMode.value.submit();
};

//image 上传
const isUp = ref(false);
const afterRead1 = (file) => {
  isUp.value = true;
  uni.uploadFile({
    url: base_URL + "/app/product/image",
    filePath: fileList.value[0].content,
    header: {
      "X-Auth-Token": uni.getStorageSync("X-Auth-Token"),
    },
    name: "file",
    success: (res) => {
      const data = JSON.parse(res.data);
      if (data.code == 200) {
        form.value.image = data.data.url;
        isUp.value = false;
      } else {
        uni.showToast({
          title: data.msg,
          icon: "none",
        });
        isUp.value = false;
      }
    },
    fail: (err) => {
      isUp.value = false;
      console.error("上传失败", err);
    },
  });
};
const deleteFile = (e) => {
  form.value.image = "";
};
const failedFun = (E) => {
  // cons;
  showToast(E.errors[0].message);
};
const onSubmit = async (values) => {
  console.log("提交", values);
  if (isUp.value) {
    return showToast("图片上传中,请稍后");
  }
  if (!form.value.image > 0) {
    return showToast("请上传商品图");
  }
  // if (fileList.value.length > 0) {
  //   console.log(fileList.value);
  //   let flie = fileList.value[0].file;

  //   const formData = new FormData();
  //   formData.append("file", flie);
  //   console.log(flie, "flie", flie.path);
  // }
  console.log(form.value.checked);
  if (!form.value.checked) {
    form.value.memberPrice = 0;
  } else {
  }
  if (!checked.value) {
    form.value.barCode = "";
    if (form.value.barCodeList.length > 0) {
      form.value.barCodeList = [];
    }
  } else {
  }

  if (type.value == "add") {
    try {
      let res = await productCreate(form.value);
      console.log(res);
      if (res.code == 200) {
        showToast("添加成功");
        uni.navigateBack();
      } else {
        showToast(res.msg);
      }
    } catch (e) {
      showToast(e.msg);
    }
  } else {
    form.value.barCode = form.value.barCodeList;

    try {
      let res = await productUpdate(form.value);
      console.log(res);
      if (res.code == 200) {
        showToast("修改成功");
        console.log(pageslenght.value);

        uni.navigateBack();
      } else {
        showToast(res.msg);
      }
    } catch (e) {
      showToast(e.msg);
    }
  }
};
async function base64ToTempFilePath(base64Data) {
  const fs = uni.getFileSystemManager();
  const fileName = "LotteryActivity_" + Date.now() + ".png"; // 自定义文件名，可根据需要修改
  console.log("23234324", uni.env);
  const filePath = uni.env.USER_DATA_PATH + "/" + fileName;
  console.log("232343245");
  const base64 = base64Data.split(",")[1]; //移除固定头部
  const buffer = uni.base64ToArrayBuffer(base64);
  let promise = await new Promise((resolve, reject) => {
    fs.writeFile({
      filePath,
      data: buffer,
      encoding: "binary",
      success(res) {
        resolve(filePath); // fulfilled
      },
      fail(err) {
        reject(err); // rejected
      },
    });
  });
  return promise;
}

//金额校验
const validator = (val) => {
  let arr = /^\d+(\.\d{1,2})?$/.test(val);
  console.log(arr, val);
  return arr;
};
//金额校验
const validatortwo = (val) => {
  let arr = /^\d+(\.\d{1,2})?$/.test(val);
  console.log(arr, val);

  if (!val) {
    return true;
  } else {
    return arr;
  }
};

//商品分类
const categoryList = ref([]);
const customFieldName = ref({
  text: "name",
  value: "id",
  children: "children",
});
const getAppCategory = async () => {
  try {
    let res = await appCategory();

    let arr = [];
    let newArr = [];
    let newArr2 = [];

    res.data.forEach((item, index) => {
      if (!item.parentId) {
        arr.push({ ...item, select: false, children: [] });
      } else {
        newArr.push({ ...item });
      }
    });
    arr.forEach((item, index) => {
      newArr.forEach((item2, index2) => {
        if (item.id == item2.parentId) {
          // item2.children = item.children || [];

          item.children.push({ ...item2, select: false, children: [] });
          newArr.splice(index2, 1);
        }
      });
    });
    arr.forEach((item, index) => {
      item.children.forEach((element, index) => {
        newArr.forEach((item2, index2) => {
          if (element.id == item2.parentId) {
            element.children.push({ ...item2, select: false });
          }
        });
      });
    });
    columns.value = arr;
  } catch (e) {}
};

//获取供应商
const supplierList = ref([]);
const supplierFieldName = ref({
  text: "name",
  value: "id",
  children: "children",
});
// const columns = ref([]);
const supplierPicker = ref(false);
const supplierValue = ref([]);
const pickerUnitValue = ref([]);
const supplierUnitName = ref({
  text: "name",
  value: "id",
  children: "children",
});

const getSupplierSelector = async () => {
  try {
    let res = await supplierSelector({ pageIndex: 1, pageSize: 999 });
    supplierList.value = res.data.datas;
  } catch (e) {}
};

const onSupplierCareConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.supplierName = selectedOptions[0]?.name;
  form.value.supplierId = selectedValues[0];
  supplierValue.value = selectedValues;
  supplierPicker.value = false;
};
const onCareUnitConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  form.value.unit = selectedOptions[0]?.name;
  // form.value.unit = selectedValues[0];
  pickerUnitValue.value = selectedValues;
  showUnitPicker.value = false;
};
const onSwitchChange = (e) => {
  console.log(e);
  if (e) {
    purchasePricevalue.value = form.value.purchasePrice;
  } else {
    purchasePricevalue.value = 0;
  }
};

//商品禁用
const availableFun = async (item) => {
  if (item) {
    try {
      let res = await appProductDisable({ id: form.value.id });
      if (res.code == 200) {
        form.value.available = !form.value.available;
        showToast("禁用成功");
        uni.reLaunch({ url: "/pages/goods/goods_list/index" });
      } else {
        showToast("禁用失败");
      }
    } catch (e) {
      showToast(e.msg);
    }
  } else {
    try {
      let res = await appProductEnable({ id: form.value.id });
      if (res.code == 200) {
        form.value.available = !form.value.available;
        showToast("启用成功");
      } else {
        showToast("启用失败");
      }
    } catch (e) {
      showToast(e.msg);
    }
  }
};

const selectBarCodeItem = ref("");
const selectBarCodeindex = ref("");
const isnewBarCode = ref(false);
const showBarCodeFun = (item, index) => {
  isnewBarCode.value = false;
  showBarCode.value = true;
  selectBarCodeItem.value = item;
  selectBarCodeindex.value = index;
};
const scanCodeTwo = async () => {
  console.log("生成");
  try {
    let res = await appProductCode();
    console.log(res);
    if (res.code == 200) {
      // form.value.barCode = res.data.code;
      selectBarCodeItem.value = res.data.code;
    } else {
      showToast(res.msg);
    }
  } catch (error) {}
};
const addBarCodeItem = () => {
  form.value.barCodeList[selectBarCodeindex.value] = selectBarCodeItem.value;
  showBarCode.value = false;
};
const addBarCode = () => {
  isnewBarCode.value = true;
  selectBarCodeItem.value = "";
  selectBarCodeindex.value = form.value.barCodeList.length;
  showBarCode.value = true;
};
const delBarCodeFun = () => {
  form.value.barCodeList.splice(selectBarCodeindex.value, 1);
  showBarCode.value = false;
  console.log("删除");
};
</script>

<template>
  <topNav
    :title="type == 'add' ? '商品添加' : '商品编辑'"
    @save="saveFun"
    rType="save"
  ></topNav>
  <view class="goods_form">
    <van-form
      @failed="failedFun"
      @submit="onSubmit"
      ref="formMode"
      :input-align="type == 'add' ? 'right' : 'left'"
      error-message-align="right"
      :show-error-message="false"
    >
      <van-field
        v-model="form.name"
        :required="true"
        name="name"
        label="商品名称"
        placeholder="请填写商品名称"
        :rules="[{ required: true, message: '请填写商品名称' }]"
      />
      <van-field
        name="image"
        :required="true"
        label="商品主图"
        :rules="[{ required: true, message: '请选择商品主图' }]"
      >
        <template #input>
          <van-uploader
            v-model="fileList"
            multiple
            :max-count="1"
            :after-read="afterRead1"
            @delete="deleteFile"
          />
        </template>
      </van-field>
      <van-field
        v-model="form.categoryName"
        is-link
        readonly
        :required="true"
        name="categoryName"
        label="归属分类"
        placeholder="点击选择"
        @click="showPicker = true"
        :rules="[{ required: true, message: '请选择归属分类' }]"
      />
      <van-field
        v-if="type != 'add'"
        name="valuationType"
        :required="true"
        label="计件方式"
        :disabled="type == 'add' ? false : true"
      >
        <template #input>
          <text style="color: #c8c9cc">{{
            form.valuationType == 1
              ? "计件"
              : form.valuationType == 2
              ? "定重(kg)"
              : "称重(kg)"
          }}</text>
          <text style="color: #c8c9cc; margin-left: 20rpx">(不可修改)</text>
        </template>
      </van-field>

      <van-field
        v-if="type != 'add' && form.barCode"
        name="barCode"
        :required="true"
        label="商品条码"
        :disabled="type == 'add' ? false : true"
      >
        <template #input>
          <text class="no-barcode">{{ form.barCode }}</text>
        </template>
      </van-field>
      <van-field
        v-if="type != 'add' && !form.barCode"
        name="dhCode"
        :required="true"
        label="称码"
        :disabled="type == 'add' ? false : true"
      >
        <template #input>
          <text class="no-barcode">{{ form.dhCode }}</text>
        </template>
      </van-field>
      <van-field
        v-if="type == 'add'"
        name="switch"
        label="是否有条码"
        :required="true"
      >
        <template #input>
          <van-switch
            v-model="checked"
            active-color="#00B42A"
            inactive-color="#dcdee0"
          />
        </template>
      </van-field>
      <van-field
        v-if="type == 'add' && checked"
        :class="type == 'add' ? '' : 'goods_form_item-noR'"
        v-model="form.barCode"
        :required="true"
        :disabled="type == 'add' ? false : true"
        name="barCode"
        label="条码"
        placeholder="条码唯一"
        :rules="[{ required: true, message: '请填写商品条码' }]"
      >
        <template #button v-if="type == 'add'">
          <view class="botton-right"
            ><view class="botton-in" @click="scanCode">生成</view>
            <view class="input-h"></view
            ><van-icon
              @click="shaScanCode"
              color="#1679fb"
              size="32rpx"
              name="scan"
          /></view>
        </template>
        <template #button v-if="type != 'add'">
          <view class="botton-right">
            <view class="input-on">不可改</view></view
          >
        </template>
      </van-field>
      <van-field
        v-model="form.salePrice"
        :required="true"
        name="salePrice"
        label="商品售价"
        placeholder="请填写商品售价"
        type="number"
        :rules="[{ validator, message: '请输入正确金额' }]"
      />
      <van-field
        v-model="form.purchasePrice"
        name="purchasePrice"
        label="商品进价"
        placeholder="请填写商品进价"
        type="number"
        :rules="[{ validator: validatortwo, message: '请输入正确金额' }]"
      />
      <van-field
        v-model="form.wholePrice"
        name="wholePrice"
        label="批发价"
        placeholder="请填写批发价"
        type="number"
        :rules="[{ validator: validatortwo, message: '请输入正确金额' }]"
      />
      <van-field
        v-model="form.unit"
        is-link
        readonly
        name="unit"
        label="单位"
        placeholder="点击选择单位"
        @click="showUnitPicker = true"
      />

      <van-field
        v-model="form.supplierName"
        is-link
        readonly
        name="supplierId"
        label="供应商"
        placeholder="点击选择"
        @click="supplierPicker = true"
      />
      <van-field name="memberPrice" label="会员价" class="van-field__select">
        <template #button>
          <van-switch
            v-model="form.checked"
            active-color="#00B42A"
            inactive-color="#dcdee0"
            @change="onSwitchChange"
          />
        </template>
      </van-field>
      <van-field
        v-if="form.checked"
        v-model="form.memberPrice"
        name="wholePrice"
        label="会员价"
        placeholder="请填写会员价"
        type="number"
        :rules="[{ validator: validatortwo, message: '请输入正确会员价金额' }]"
      />
      <van-field
        v-model="form.remark"
        rows="1"
        autosize
        label="说明"
        type="textarea"
        placeholder="请输入说明"
      />
      <van-field
        v-for="(item1, index1) in form.barCodeList"
        v-if="type != 'add'"
        :name="'barCode' + (index1 + 1)"
        :label="'商品条码' + (index1 + 1)"
        @click="showBarCodeFun(item1, index1)"
        is-link
        readonly
      >
        <template #input>
          <text>{{ item1 }}</text>
        </template>
      </van-field>

      <view class="add-barCode" @click="addBarCode" v-if="type != 'add'">
        <van-button type="default" class="botton-to" @click="addBarCode()">
          {{ "添加一品多码商品" }}
        </van-button>
      </view>

      <div class="foot-btn">
        <view class="foot-btn-k"
          ><van-button block type="primary" native-type="submit">
            {{ type == "add" ? "保存" : "保存" }}
          </van-button></view
        >
      </div>
    </van-form>
  </view>

  <view class="botton-bt" v-if="type != 'add'">
    <van-button
      type="default"
      class="botton-to"
      @click="availableFun(form.available)"
    >
      {{ form.available ? "禁用此商品" : "启用用此商品" }}
    </van-button>
  </view>
  <view style="width: 100%; height: 200rpx"></view>

  <van-popup v-model:show="supplierPicker" destroy-on-close position="bottom">
    <van-picker
      :model-value="supplierValue"
      :columns="supplierList"
      :columns-field-names="supplierFieldName"
      @confirm="onSupplierCareConfirm"
      @cancel="supplierPicker = false"
    />
  </van-popup>

  <van-popup v-model:show="showUnitPicker" destroy-on-close position="bottom">
    <van-picker
      :columns="unitList"
      :model-value="pickerUnitValue"
      :columns-field-names="supplierUnitName"
      @confirm="onCareUnitConfirm"
      @cancel="showUnitPicker = false"
    />
  </van-popup>
  <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
    <van-picker
      :model-value="pickerValue"
      :columns="columns"
      :columns-field-names="customFieldName"
      @confirm="onCareConfirm"
      @cancel="showPicker = false"
    />
  </van-popup>
  <van-popup
    v-model:show="showBarCode"
    destroy-on-close
    position="bottom"
    :closeable="true"
    :safe-area-inset-bottom="true"
    :round="true"
  >
    <view class="add-popup">
      <view class="title">一品多码</view>
      <view class="title-des">一个商品对应多个条码</view>
      <view class="top-hx"></view>
      <view class="add-barcode-input">
        <van-field
          v-model="selectBarCodeItem"
          name="barCodes"
          label="条码"
          placeholder="输入条码"
          :left-icon="homeStart"
        >
          <template #button>
            <view class="botton-right"
              ><view class="botton-in" @click="scanCodeTwo">生成</view>
              <view class="input-h"></view
              ><van-icon
                @click="shaScanCode"
                color="#1679fb"
                size="32rpx"
                name="scan"
            /></view>
          </template> </van-field
      ></view>
      <view class="bt-hx"></view>

      <view class="foods_bt">
        <van-button
          class="qx-bt"
          type="default"
          @click="delBarCodeFun"
          v-if="isnewBarCode == false"
          >删除</van-button
        >
        <van-button
          class="qx-bt"
          type="default"
          @click="showBarCode = false"
          v-if="isnewBarCode"
          >关闭</van-button
        >
        <van-button class="qr-bt" @click="addBarCodeItem" type="primary"
          >确认</van-button
        >
      </view>
    </view>
  </van-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
